"use client";

import { useEffect, useRef, useCallback, useState } from "react";
import { type API } from "@/lib/api";
import TerminalChat from "./TerminalChat";

interface ChatMessage {
    id: string;
    content: string;
    sender: "user" | "assistant";
    nickname?: string;
    timestamp: Date;
}

interface TerminalComponentProps {
    id: string;
    onTerminalReady?: (terminal: any) => void;
    api?: API | null;
    sessionId?: string | null;
    hasWriteAccess?: boolean;
    onInput?: (data: { id: string; data: Uint8Array }) => void;
    onResize?: (data: { id: string; rows: number; cols: number }) => void;
    onStatus?: (data: { id: string; status: string }) => void;
    fontFamily?: string;
    fontSize?: number;
    onChatMessage?: (message: string) => void;
    chatMessages?: ChatMessage[];
    showChat?: boolean;
    // WebShare properties
    onWebShare?: (data: { localPort: number; publicPort: number }) => void;
    onWebUnshare?: (data: { publicPort: number }) => void;
    sharedPorts?: Array<{ localPort: number; publicPort: number; url?: string; status?: 'active' | 'stopping' | 'error' }>;
}

// Terminal themes
const themes = {
    dark: {
        background: '#1e1e1e',
        foreground: '#ffffff',
        cursor: '#ffffff',
        selectionBackground: '#264f78',
        black: '#000000',
        red: '#cd3131',
        green: '#0dbc79',
        yellow: '#e5e510',
        blue: '#2472c8',
        magenta: '#bc3fbc',
        cyan: '#11a8cd',
        white: '#e5e5e5',
        brightBlack: '#666666',
        brightRed: '#f14c4c',
        brightGreen: '#23d18b',
        brightYellow: '#f5f543',
        brightBlue: '#3b8eea',
        brightMagenta: '#d670d6',
        brightCyan: '#29b8db',
        brightWhite: '#e5e5e5',
    }
};

export default function TerminalComponent({
    id,
    onTerminalReady,
    api: propApi,
    sessionId: propSessionId,
    hasWriteAccess = true,
    onInput,
    onResize,
    onStatus,
    fontFamily = '"Fira Code VF", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
    fontSize = 12,
    onChatMessage,
    chatMessages = [],
    showChat = true,
    onWebShare,
    onWebUnshare,
    sharedPorts = []
}: TerminalComponentProps) {
    const terminalRef = useRef<HTMLDivElement>(null);
    const terminalInstanceRef = useRef<any>(null);
    const fitAddonRef = useRef<any>(null);
    const [isClient, setIsClient] = useState(false);
    const [loaded, setLoaded] = useState(false);
    const [focused, setFocused] = useState(false);
    const [isMobile, setIsMobile] = useState(false);
    const [showShareModal, setShowShareModal] = useState(false);
    const [showStopConfirmModal, setShowStopConfirmModal] = useState(false);
    const [portToStop, setPortToStop] = useState<{ localPort: number; publicPort: number } | null>(null);
    const [shareError, setShareError] = useState<string | null>(null);
    const [shareLoading, setShareLoading] = useState(false);
    const [localPort, setLocalPort] = useState(3000);
    const [publicPort, setPublicPort] = useState(8080);
    const [virtualKeyboardVisible, setVirtualKeyboardVisible] = useState(false);

    // Input handling state
    const accumulatedInputRef = useRef<Uint8Array>(new Uint8Array(0));
    const inputDebounceTimerRef = useRef<NodeJS.Timeout | null>(null);
    const localDisplayBufferRef = useRef('');

    // Check if we're on client side and detect mobile device
    useEffect(() => {
        setIsClient(true);

        // Detect mobile device
        const checkMobile = () => {
            const isMobileDevice = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ||
                                window.innerWidth < 768;
            setIsMobile(isMobileDevice);
        };

        checkMobile();
        window.addEventListener('resize', checkMobile);

        // Detect virtual keyboard on mobile
        const handleVisualViewportChange = () => {
            if (window.visualViewport) {
                const keyboardVisible = window.visualViewport.height < window.innerHeight * 0.75;
                setVirtualKeyboardVisible(keyboardVisible);
            }
        };

        if (window.visualViewport) {
            window.visualViewport.addEventListener('resize', handleVisualViewportChange);
        }

        return () => {
            window.removeEventListener('resize', checkMobile);
            if (window.visualViewport) {
                window.visualViewport.removeEventListener('resize', handleVisualViewportChange);
            }
        };
    }, []);

    const handleTerminalInput = useCallback((data: Uint8Array) => {
        if (!hasWriteAccess) return;

        const inputText = new TextDecoder().decode(data);
        console.log(`[Terminal Debug] Input received:`, {
            data: Array.from(data),
            text: inputText,
            charCodes: inputText.split('').map(c => c.charCodeAt(0))
        });

        // Check for special keys
        const isBackspace = data.length === 1 && data[0] === 8;
        const isDelete = data.length === 1 && data[0] === 127;
        const isTab = data.length === 1 && data[0] === 9;
        const isEnterKey = (data.length === 1 && data[0] === 13) ||
            (data.length === 2 && data[0] === 13 && data[1] === 10);
        const isSpecialKey = isBackspace || isDelete || isTab || isEnterKey;

        // If we have remote API, don't do local echo - let remote handle everything
        const hasRemoteConnection = propApi && propSessionId;

        if (!hasRemoteConnection && terminalInstanceRef.current) {
            // Only do local echo when no remote connection
            if (isEnterKey) {
                terminalInstanceRef.current.write('\r\n');
                localDisplayBufferRef.current += '\r\n';
            } else if (isBackspace || isDelete) {
                if (localDisplayBufferRef.current.length > 0) {
                    terminalInstanceRef.current.write('\b \b');
                    localDisplayBufferRef.current = localDisplayBufferRef.current.slice(0, -1);
                }
            } else {
                // Echo regular input
                terminalInstanceRef.current.write(inputText);
                localDisplayBufferRef.current += inputText;
            }
        }

        // Send input event to parent
        onInput?.({ id, data });

        // Handle remote sync if API is available
        if (hasRemoteConnection) {
            handleRemoteInput(data, isSpecialKey, isEnterKey);
        }
    }, [id, hasWriteAccess, propApi, propSessionId, onInput]);

    const handleRemoteInput = useCallback(async (data: Uint8Array, isSpecialKey: boolean, isEnterKey: boolean) => {
        // Accumulate input data
        const combined = new Uint8Array(accumulatedInputRef.current.length + data.length);
        combined.set(accumulatedInputRef.current);
        combined.set(data, accumulatedInputRef.current.length);
        accumulatedInputRef.current = combined;

        if (isEnterKey) {
            // Send immediately on Enter
            clearDebounceTimer();
            await sendRemoteInput(accumulatedInputRef.current);
            accumulatedInputRef.current = new Uint8Array(0);
        } else if (isSpecialKey) {
            // Send special keys immediately
            clearDebounceTimer();
            await sendRemoteInput(accumulatedInputRef.current);
            accumulatedInputRef.current = new Uint8Array(0);
        } else {
            // Debounce regular keys for better performance
            clearDebounceTimer();
            inputDebounceTimerRef.current = setTimeout(async () => {
                await sendRemoteInput(accumulatedInputRef.current);
                accumulatedInputRef.current = new Uint8Array(0);
            }, 300); // Reduced debounce time for better responsiveness
        }
    }, [propApi, propSessionId]);

    const sendRemoteInput = useCallback(async (data: Uint8Array) => {
        if (!propApi || !propSessionId) return;

        try {
          console.log(`Sending input for terminal ${id}: ${data.length} bytes`);
            await propApi.sendTerminalInput(propSessionId, id, data);
            console.log(`Sent input for terminal ${id}: ${data.length} bytes`);
        } catch (error) {
            console.error('Failed to send terminal input:', error);
        }
    }, [propApi, propSessionId, id]);

    const clearDebounceTimer = useCallback(() => {
        if (inputDebounceTimerRef.current) {
            clearTimeout(inputDebounceTimerRef.current);
            inputDebounceTimerRef.current = null;
        }
    }, []);

    // WebShare handlers with enhanced error handling
    const handleSharePort = useCallback(async () => {
        if (!propApi || !propSessionId) return;

        setShareLoading(true);
        setShareError(null);

        try {
            await onWebShare?.({ localPort, publicPort });
            setShowShareModal(false);
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to share port';
            setShareError(errorMessage);
            console.error('Failed to share port:', error);
        } finally {
            setShareLoading(false);
        }
    }, [propApi, propSessionId, localPort, publicPort, onWebShare]);

    const handleUnsharePort = useCallback(async (publicPortToUnshare: number, immediate = false) => {
        if (!propApi || !propSessionId) return;

        // If not immediate, show confirmation dialog
        if (!immediate) {
            const port = sharedPorts.find(p => p.publicPort === publicPortToUnshare);
            if (port) {
                setPortToStop({ localPort: port.localPort, publicPort: publicPortToUnshare });
                setShowStopConfirmModal(true);
                return;
            }
        }

        try {
            await onWebUnshare?.({ publicPort: publicPortToUnshare });
        } catch (error) {
            console.error('Failed to unshare port:', error);
        }
    }, [propApi, propSessionId, onWebUnshare, sharedPorts]);

    const confirmStopSharing = useCallback(async () => {
        if (!portToStop) return;

        try {
            await onWebUnshare?.({ publicPort: portToStop.publicPort });
            setShowStopConfirmModal(false);
            setPortToStop(null);
        } catch (error) {
            console.error('Failed to stop sharing:', error);
        }
    }, [portToStop, onWebUnshare]);

    const copyToClipboard = useCallback(async (text: string) => {
        try {
            await navigator.clipboard.writeText(text);
            // You could add a toast notification here
        } catch (error) {
            console.error('Failed to copy to clipboard:', error);
        }
    }, []);

    const getShareUrl = useCallback((publicPortNum: number) => {
        const protocol = window.location.protocol;
        const host = window.location.hostname;
        return `${protocol}//${host}:${publicPortNum}`;
    }, []);


    // Helper to strip ANSI codes for comparison
    const stripAnsi = useCallback((str: string): string => {
        return str.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
            .replace(/\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g, '')
            .replace(/\x1b[=>]/g, '')
            .replace(/\x1b[()][AB012]/g, '');
    }, []);

    const processRemoteOutput = useCallback((output: string) => {
        if (!terminalInstanceRef.current) return;

        console.log(`[Terminal Debug] Remote output received:`, {
            output: output.substring(0, 100),
            charCodes: output.split('').map(c => c.charCodeAt(0))
        });

        // Simply display remote output - no local echo to clear since we disabled it
        console.log('[Terminal Debug] Displaying remote output directly');
        terminalInstanceRef.current.write(output);
    }, []);

    // Initialize terminal with duplicate prevention
    useEffect(() => {
        if (!terminalRef.current || !isClient || terminalInstanceRef.current) return;

        const initializeTerminal = async () => {
            try {
                // Dynamically import xterm modules
                const [
                    { Terminal },
                    { FitAddon },
                    { WebLinksAddon },
                    // { WebglAddon },
                    { ImageAddon }
                ] = await Promise.all([
                    import('@xterm/xterm'),
                    import('@xterm/addon-fit'),
                    import('@xterm/addon-web-links'),
                    // import('@xterm/addon-webgl'),
                    import('@xterm/addon-image')
                ]);

                // Mobile-responsive terminal configuration
                const mobileFontSize = isMobile ? Math.max(10, fontSize - 2) : fontSize;
                const mobileCols = isMobile ? Math.max(40, Math.floor(window.innerWidth / 8)) : 80;
                const mobileRows = isMobile ? Math.max(10, Math.floor((window.innerHeight - 200) / 20)) : 24;

                const terminal = new Terminal({
                    allowTransparency: false,
                    cursorBlink: !isMobile, // Disable cursor blink on mobile for better performance
                    cursorStyle: 'block',
                    fontFamily,
                    fontSize: mobileFontSize,
                    fontWeight: 400,
                    fontWeightBold: 500,
                    lineHeight: 1.2,
                    scrollback: isMobile ? 500 : 1000, // Reduced scrollback on mobile
                    theme: themes.dark,
                    cols: mobileCols,
                    rows: mobileRows,
                    wordWrap: isMobile, // Enable word wrap on mobile
                    convertEol: true,
                    rightClickSelectsWord: !isMobile, // Disable on mobile for better touch support
                });

                // Load addons
                const fitAddon = new FitAddon();
                const webLinksAddon = new WebLinksAddon();
                const imageAddon = new ImageAddon({ enableSizeReports: false });

                terminal.loadAddon(fitAddon);
                terminal.loadAddon(webLinksAddon);
                terminal.loadAddon(imageAddon);

                // Disable WebGL addon to prevent context warnings
                // Canvas renderer is more efficient for multiple terminals

                terminal.open(terminalRef.current!);
                fitAddon.fit();

                // Handle resize with mobile optimizations
                const handleResize = () => {
                    if (fitAddon && terminalRef.current) {
                        const containerRect = terminalRef.current.getBoundingClientRect();
                        const isLandscape = window.innerWidth > window.innerHeight;

                        // Mobile-specific sizing
                        let maxWidth, maxHeight;
                        if (isMobile) {
                            if (isLandscape) {
                                maxWidth = Math.min(containerRect.width - 16, window.innerWidth - 100);
                                maxHeight = Math.min(containerRect.height - 16, window.innerHeight - 300);
                            } else {
                                maxWidth = Math.min(containerRect.width - 16, window.innerWidth - 50);
                                maxHeight = Math.min(containerRect.height - 16, window.innerHeight - virtualKeyboardVisible ? 400 : 200);
                            }
                        } else {
                            maxWidth = Math.min(containerRect.width - 16, 800);
                            maxHeight = Math.min(containerRect.height - 16, 500);
                        }

                        // Constrain terminal size
                        if (maxWidth > 0 && maxHeight > 0) {
                            fitAddon.fit();
                            const { rows, cols } = terminal;

                            // Mobile constraints
                            let constrainedCols, constrainedRows;
                            if (isMobile) {
                                constrainedCols = Math.min(cols, isLandscape ? 120 : 60);
                                constrainedRows = Math.min(rows, isLandscape ? 30 : 20);
                            } else {
                                constrainedCols = Math.min(cols, 120);
                                constrainedRows = Math.min(rows, 40);
                            }

                            if (cols !== constrainedCols || rows !== constrainedRows) {
                                terminal.resize(constrainedCols, constrainedRows);
                            }

                            onResize?.({ id, rows: constrainedRows, cols: constrainedCols });
                        }
                    }
                };

                // Initial fit and resize handler
                handleResize();
                window.addEventListener("resize", handleResize);

                // Handle user input
                const utf8Encoder = new TextEncoder();
                terminal.onData((data: string) => {
                    handleTerminalInput(utf8Encoder.encode(data));
                });

                terminal.onBinary((data: string) => {
                    handleTerminalInput(new TextEncoder().encode(data));
                });

                // Add touch gesture support for mobile
                if (isMobile && terminalRef.current) {
                    let touchStartTime = 0;
                    let touchStartY = 0;
                    let longPressTimer: NodeJS.Timeout | null = null;

                    const handleTouchStart = (e: TouchEvent) => {
                        touchStartTime = Date.now();
                        touchStartY = e.touches[0].clientY;

                        // Long press detection
                        longPressTimer = setTimeout(() => {
                            // Show context menu or handle long press
                            e.preventDefault();
                        }, 500);
                    };

                    const handleTouchEnd = (e: TouchEvent) => {
                        if (longPressTimer) {
                            clearTimeout(longPressTimer);
                            longPressTimer = null;
                        }

                        const touchDuration = Date.now() - touchStartTime;
                        const touchEndY = e.changedTouches[0].clientY;
                        const touchDeltaY = Math.abs(touchEndY - touchStartY);

                        // Handle short tap (not scroll)
                        if (touchDuration < 200 && touchDeltaY < 10) {
                            // Focus terminal
                            terminal.focus();
                        }
                    };

                    const handleTouchMove = (e: TouchEvent) => {
                        if (longPressTimer) {
                            clearTimeout(longPressTimer);
                            longPressTimer = null;
                        }
                    };

                    terminalRef.current.addEventListener('touchstart', handleTouchStart, { passive: false });
                    terminalRef.current.addEventListener('touchend', handleTouchEnd, { passive: true });
                    terminalRef.current.addEventListener('touchmove', handleTouchMove, { passive: true });
                }

                // Handle focus changes
                terminal.onTitleChange((title: string) => {
                    console.log(`Terminal ${id} title changed: ${title}`);
                });

                terminalInstanceRef.current = terminal;
                fitAddonRef.current = fitAddon;

                // Expose methods to parent
                if (onTerminalReady) {
                    (terminal as any).processRemoteOutput = processRemoteOutput;
                    onTerminalReady(terminal);
                }

                setLoaded(true);

                return () => {
                    console.log(`🧹 Cleaning up terminal ${id}`);
                    window.removeEventListener("resize", handleResize);
                    if (terminalInstanceRef.current) {
                        terminalInstanceRef.current.dispose();
                        terminalInstanceRef.current = null;
                    }
                    clearDebounceTimer();
                };
            } catch (error) {
                console.error('Failed to initialize terminal:', error);
            }
        };

        initializeTerminal();
    }, [id, isClient, handleTerminalInput, processRemoteOutput, onResize, onTerminalReady]);

    // Update font settings when they change (with mobile optimization)
    useEffect(() => {
        if (terminalInstanceRef.current) {
            terminalInstanceRef.current.options.fontFamily = fontFamily;
            const adjustedFontSize = isMobile ? Math.max(10, fontSize - 2) : fontSize;
            terminalInstanceRef.current.options.fontSize = adjustedFontSize;
            // Refresh the terminal to apply changes
            terminalInstanceRef.current.refresh(0, terminalInstanceRef.current.rows - 1);
        }
    }, [fontFamily, fontSize, isMobile]);

    // Cleanup on unmount
    useEffect(() => {
        return () => {
            clearDebounceTimer();
        };
    }, [clearDebounceTimer]);

    if (!isClient) {
        return (
            <div className={`flex flex-col h-full bg-gray-950 rounded-lg overflow-hidden shadow-xl ${isMobile ? 'h-screen' : ''}`}>
                {/* Terminal Header */}
                <div className="bg-gray-800 px-3 py-2 border-b border-gray-700">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-2">
                            <div className="flex items-center space-x-1">
                                <div className="w-3 h-3 bg-red-500 rounded-full"></div>
                                <div className="w-3 h-3 bg-yellow-500 rounded-full"></div>
                                <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                            </div>
                            <div className="h-4 w-px bg-gray-600 hidden sm:block"></div>
                            <div className="text-sm font-medium text-gray-300 truncate">
                                Terminal {id}
                            </div>
                        </div>
                        <div className="flex items-center space-x-2">
                            <div className="flex items-center space-x-1">
                                <div className="w-2 h-2 bg-yellow-500 rounded-full animate-pulse"></div>
                                <span className="text-xs text-gray-400 hidden sm:inline">Loading...</span>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Terminal Area */}
                <div className="flex-1 flex flex-col min-h-0">
                    <div className="flex-1 flex items-center justify-center bg-gray-900">
                        <div className="text-center">
                            <div className={`w-8 h-8 border-2 border-gray-600 border-t-blue-500 rounded-full animate-spin mx-auto mb-3 ${isMobile ? 'w-6 h-6 mb-2' : ''}`}></div>
                            <div className={`text-gray-400 text-sm ${isMobile ? 'text-xs' : ''}`}>Initializing terminal...</div>
                        </div>
                    </div>

                    {/* Terminal Chat */}
                    {showChat && (
                        <div className={isMobile ? 'h-48' : ''}>
                            <TerminalChat
                                onSendMessage={onChatMessage || (() => { })}
                                messages={chatMessages}
                                disabled={!propApi || !propSessionId}
                                placeholder={isMobile ? "Ask AI..." : "Ask AI assistant..."}
                                minHeight={isMobile ? "180px" : "200px"}
                                maxHeight={isMobile ? "250px" : "300px"}
                            />
                        </div>
                    )}
                </div>
            </div>
        );
    }

    return (
        <div className={`flex flex-col h-full bg-gray-950 rounded-lg overflow-hidden shadow-xl ${isMobile ? 'h-screen' : ''}`}>
            {/* Terminal Header */}
            <div className="bg-gray-800 px-3 py-2 border-b border-gray-700">
                <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                        <div className="flex items-center space-x-1">
                            <div className="w-3 h-3 bg-red-500 rounded-full hover:bg-red-400 transition-colors cursor-pointer"></div>
                            <div className="w-3 h-3 bg-yellow-500 rounded-full hover:bg-yellow-400 transition-colors cursor-pointer"></div>
                            <div className="w-3 h-3 bg-green-500 rounded-full hover:bg-green-400 transition-colors cursor-pointer"></div>
                        </div>
                        <div className="h-4 w-px bg-gray-600 hidden sm:block"></div>
                        <div className="text-sm font-medium text-gray-300 truncate">
                            Terminal {id}
                        </div>
                    </div>
                    <div className="flex items-center space-x-1">
                        {/* WebShare Button */}
                        <button
                            onClick={() => setShowShareModal(true)}
                            className={`p-1.5 rounded-md transition-colors ${hasWriteAccess
                                ? 'bg-blue-600 hover:bg-blue-700 text-white'
                                : 'bg-gray-600 hover:bg-gray-700 text-gray-300 opacity-50 cursor-not-allowed'
                            } ${isMobile ? 'px-2 py-1' : 'px-3 py-1.5'}`}
                            disabled={!hasWriteAccess}
                            title="Share Port"
                        >
                            <svg className={`w-4 h-4 ${isMobile ? 'w-3 h-3' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.367 2.684 3 3 0 00-5.367-2.684z" />
                            </svg>
                            {!isMobile && <span className="ml-1 text-xs">Share</span>}
                        </button>

                        {propApi && propSessionId && (
                            <div className="flex items-center space-x-1">
                                <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
                                <span className="text-xs text-gray-400 hidden sm:inline">Connected</span>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* Terminal Area */}
            <div className="flex-1 flex flex-col min-h-0">
                <div
                    ref={terminalRef}
                    className={`flex-1 p-2 sm:p-3 overflow-x-hidden overflow-y-auto transition-all duration-200 ${focused ? 'ring-2 ring-blue-500/20' : ''
                        } ${isMobile ? 'pb-16' : ''}`}
                    style={{
                        minHeight: isMobile ? "200px" : "300px",
                        width: "100%",
                        backgroundColor: themes.dark.background,
                        fontSize: isMobile ? '12px' : '14px'
                    }}
                    onFocus={() => setFocused(true)}
                    onBlur={() => setFocused(false)}
                />

                {/* Shared Ports List */}
                {sharedPorts.length > 0 && (
                    <div className="border-t border-gray-700 bg-gray-800 px-3 py-2">
                        <div className="flex items-center justify-between mb-2">
                            <div className="text-xs font-medium text-gray-400">Shared Ports</div>
                            <div className="text-xs text-gray-500">{sharedPorts.length} active</div>
                        </div>
                        <div className="space-y-2">
                            {sharedPorts.map((port, index) => (
                                <div key={index} className="bg-gray-700 rounded-md p-2">
                                    <div className="flex items-center justify-between mb-1">
                                        <div className="flex items-center space-x-2">
                                            {/* Status indicator */}
                                            <div className={`w-2 h-2 rounded-full ${
                                                port.status === 'active' ? 'bg-green-500' :
                                                port.status === 'stopping' ? 'bg-yellow-500 animate-pulse' :
                                                'bg-red-500'
                                            }`} />
                                            <span className="text-xs text-gray-300 font-mono">
                                                localhost:{port.localPort} → <span className="text-blue-400">:{port.publicPort}</span>
                                            </span>
                                        </div>
                                        <div className="flex items-center space-x-1">
                                            {port.url && (
                                                <button
                                                    onClick={() => copyToClipboard(port.url!)}
                                                    className="p-1 text-gray-400 hover:text-white transition-colors rounded"
                                                    title="Copy URL"
                                                    disabled={port.status === 'stopping'}
                                                >
                                                    <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                                                    </svg>
                                                </button>
                                            )}
                                            <button
                                                onClick={() => handleUnsharePort(port.publicPort)}
                                                className={`p-1 rounded transition-colors ${
                                                    port.status === 'stopping'
                                                        ? 'text-gray-500 cursor-not-allowed'
                                                        : 'text-red-400 hover:text-red-300 hover:bg-red-900/20'
                                                }`}
                                                title={port.status === 'stopping' ? 'Stopping...' : 'Stop sharing'}
                                                disabled={port.status === 'stopping'}
                                            >
                                                {port.status === 'stopping' ? (
                                                    <svg className="w-3 h-3 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                                    </svg>
                                                ) : (
                                                    <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                                    </svg>
                                                )}
                                            </button>
                                        </div>
                                    </div>
                                    {port.url && (
                                        <div className="text-xs text-gray-400 truncate">
                                            <span className="text-blue-400">{port.url}</span>
                                        </div>
                                    )}
                                    {port.status === 'stopping' && (
                                        <div className="text-xs text-yellow-400 mt-1">
                                            Stopping share...
                                        </div>
                                    )}
                                    {port.status === 'error' && (
                                        <div className="text-xs text-red-400 mt-1">
                                            Error stopping share
                                        </div>
                                    )}
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* Terminal Chat */}
                {showChat && (
                    <div className={`${isMobile ? 'h-48' : ''}`}>
                        <TerminalChat
                            onSendMessage={onChatMessage || (() => { })}
                            messages={chatMessages}
                            disabled={!propApi || !propSessionId}
                            placeholder={isMobile ? "Ask AI..." : "Ask AI assistant..."}
                            minHeight={isMobile ? "180px" : "200px"}
                            maxHeight={isMobile ? "250px" : "300px"}
                        />
                    </div>
                )}
            </div>

            {/* WebShare Modal */}
            {showShareModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
                    <div className={`bg-gray-800 rounded-lg p-4 sm:p-6 w-full max-w-md ${isMobile ? 'max-h-[90vh] overflow-y-auto' : ''}`}>
                        <div className="flex items-center justify-between mb-4">
                            <h3 className="text-lg font-semibold text-white">Share Port</h3>
                            <button
                                onClick={() => {
                                    setShowShareModal(false);
                                    setShareError(null);
                                }}
                                className="text-gray-400 hover:text-white transition-colors"
                            >
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>

                        {/* Error Display */}
                        {shareError && (
                            <div className="mb-4 p-3 bg-red-900/50 border border-red-500 rounded-md">
                                <div className="text-sm text-red-400">{shareError}</div>
                            </div>
                        )}

                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-300 mb-1">
                                    Local Port
                                </label>
                                <input
                                    type="number"
                                    value={localPort}
                                    onChange={(e) => setLocalPort(parseInt(e.target.value) || 3000)}
                                    className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    min="1"
                                    max="65535"
                                    disabled={shareLoading}
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-300 mb-1">
                                    Public Port
                                </label>
                                <input
                                    type="number"
                                    value={publicPort}
                                    onChange={(e) => setPublicPort(parseInt(e.target.value) || 8080)}
                                    className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    min="1"
                                    max="65535"
                                    disabled={shareLoading}
                                />
                            </div>

                            <div className="bg-gray-700 rounded-md p-3">
                                <div className="text-sm text-gray-300">
                                    <div className="font-medium mb-1">Share URL:</div>
                                    <div className="text-xs text-blue-400 break-all">
                                        {getShareUrl(publicPort)}
                                    </div>
                                </div>
                            </div>

                            <div className="flex space-x-3">
                                <button
                                    onClick={handleSharePort}
                                    disabled={shareLoading}
                                    className={`flex-1 font-medium py-2 px-4 rounded-md transition-colors ${
                                        shareLoading
                                            ? 'bg-gray-600 text-gray-400 cursor-not-allowed'
                                            : 'bg-blue-600 hover:bg-blue-700 text-white'
                                    }`}
                                >
                                    {shareLoading ? (
                                        <div className="flex items-center justify-center">
                                            <svg className="w-4 h-4 animate-spin mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                            </svg>
                                            Sharing...
                                        </div>
                                    ) : (
                                        'Share Port'
                                    )}
                                </button>
                                <button
                                    onClick={() => {
                                        setShowShareModal(false);
                                        setShareError(null);
                                    }}
                                    disabled={shareLoading}
                                    className="flex-1 bg-gray-600 hover:bg-gray-700 text-white font-medium py-2 px-4 rounded-md transition-colors disabled:opacity-50"
                                >
                                    Cancel
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Stop Sharing Confirmation Modal */}
            {showStopConfirmModal && portToStop && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
                    <div className={`bg-gray-800 rounded-lg p-4 sm:p-6 w-full max-w-sm ${isMobile ? 'max-h-[90vh] overflow-y-auto' : ''}`}>
                        <div className="flex items-center justify-center mb-4">
                            <div className="w-12 h-12 bg-red-500/20 rounded-full flex items-center justify-center">
                                <svg className="w-6 h-6 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                                </svg>
                            </div>
                        </div>

                        <h3 className="text-lg font-semibold text-white text-center mb-2">
                            Stop Sharing Port
                        </h3>

                        <div className="text-center mb-6">
                            <p className="text-gray-300 mb-3">
                                Are you sure you want to stop sharing this port?
                            </p>
                            <div className="bg-gray-700 rounded-md p-3">
                                <div className="text-sm text-gray-300">
                                    <div className="font-mono text-blue-400">
                                        localhost:{portToStop.localPort} → :{portToStop.publicPort}
                                    </div>
                                    <div className="text-xs text-gray-400 mt-1">
                                        {getShareUrl(portToStop.publicPort)}
                                    </div>
                                </div>
                            </div>
                            <p className="text-xs text-orange-400 mt-3">
                                This will make the service inaccessible from the internet.
                            </p>
                        </div>

                        <div className="flex space-x-3">
                            <button
                                onClick={confirmStopSharing}
                                className="flex-1 bg-red-600 hover:bg-red-700 text-white font-medium py-2 px-4 rounded-md transition-colors"
                            >
                                Stop Sharing
                            </button>
                            <button
                                onClick={() => {
                                    setShowStopConfirmModal(false);
                                    setPortToStop(null);
                                }}
                                className="flex-1 bg-gray-600 hover:bg-gray-700 text-white font-medium py-2 px-4 rounded-md transition-colors"
                            >
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
